"""
调用TTS例子的UI层。
"""
import typing

from elio import core


class TtsLayer(core.AutoRecycleLayer[core.Activity]):
    tts: core.TextToSpeech
    editor: core.WidgetEditor
    btnSpeak: core.WidgetButton

    async def on_create(self, *args: typing.Any, **kwargs: typing.Dict):
        await super().on_create(*args, *kwargs)
        activity = self.parent
        # TTS测试
        self.tts = await core.TextToSpeech.create(activity, None)

        async def cb_start(utterance_id: str):
            """
            开始朗读事件。
            :param utterance_id: 朗读ID。
            """
            print('Start speaking', utterance_id)

        await self.tts.set_on_start_listener(cb_start)

        async def cb_stop(utterance_id: str):
            """
            停止朗读事件。
            :param utterance_id: 朗读ID
            """
            print('Stop speaking', utterance_id)

        await self.tts.set_on_stop_listener(cb_stop)

        async def cb_done(utterance_id: str):
            """
            朗读完毕事件。
            :param utterance_id: 朗读ID。
            """
            print('Speak done', utterance_id)

        await self.tts.set_on_done_listener(cb_done)

        async def cb_error(utterance_id: str):
            """
            朗读出错事件。
            :param utterance_id: 朗读ID。
            """
            print('Speak error', utterance_id)

        await self.tts.set_on_error_listener(cb_error)

    async def on_hide(self):
        await super().on_hide()
        await self.editor.destroy()
        await self.btnSpeak.destroy()

    async def on_show(self):
        await super().on_show()
        activity = self.parent
        width, height = await activity.get_screen_size()
        # 创建一个编辑框
        self.editor = await core.WidgetEditor.create(activity, width, 500, 0, 0, '你好，这是一段测试文本。')
        await self.editor.set_hint('请输入合成文本')
        self.btnSpeak = await core.WidgetButton.create(activity, width, 200, 0, 500, '朗读')

        async def cb_speak():
            """
            朗读按钮点击事件。
            """
            await self.tts.speak(await self.editor.get_text(), 'test')

        await self.btnSpeak.set_on_click_listener(cb_speak)

    async def on_pause(self):
        await super().on_pause()

    async def on_resume(self):
        await super().on_resume()

    async def on_destroy(self, *args: typing.Any, **kwargs: typing.Dict):
        await super().on_destroy(*args, **kwargs)
